
#include "PlayerGift.h"
#include "Common.h"
#include "Config.h"
#include "MySQLConnection.h"
#include "Player.h"
#include "PlayerGift.h"

LevelUpGift::LevelUpGift(string aSubject, string aBody, uint32 aTargetLevel, uint32 aSenderGuid)
{
    subject = aSubject;
    body = aBody;
    targetLevel = aTargetLevel;
    senderGuid = aSenderGuid;
    money = 0;
}
LevelUpGift::~LevelUpGift(){
    if(giftItems.size() >= 0){
        for(LeveUpGiftEntry* entry : giftItems){
            delete entry;
        }
        giftItems.clear();
    }
}
void LevelUpGift::setMonney(uint32 moneyPrice)
{
    money = moneyPrice;
}

void LevelUpGift::addGift(LeveUpGiftEntry *giftEntry)
{
    giftItems.push_back(giftEntry);
}
void LevelUpGift::mailTo(Player *player)
{
    if (player == nullptr) {
        LOG_WARN("kkk gift module.sendgift", ">> player is null!");
        return;
    }
    MailDraft draft(getSubject(), getBody());

    CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction();
    const std::vector<LeveUpGiftEntry*> giftItems = getGifts();
    if (!giftItems.empty()) {
        for (LeveUpGiftEntry *giftEntry : giftItems) {
            if(giftEntry->getType() == KKK_GIFT_TYPE_ITEM){
                Item *item = Item::CreateItem(giftEntry->getItemId(), giftEntry->getCount());
                if (item) {
                    item->SaveToDB(trans);
                    draft.AddItem(item);
                }
            }else if(giftEntry->getType() == KKK_GIFT_TYPE_RENAME){
                player->UpdatePlayerSetting(KKK_GIFT_SOURCE,KKK_GIFT_RENAME_INX,1);
            }
            
            
        }
    }
    draft.AddMoney(getMoney());
    draft.SendMailTo(trans, player, MailSender(MAIL_NORMAL, getSenderGuid()));
    CharacterDatabase.CommitTransaction(trans);
}


void PlayerGiftCenter::clear(){
    int i = 0;
    //free gift array
    for (i = 0; i < levelupGiftArray.size(); i++) {
        LevelUpGift *gift = levelupGiftArray[i];
        if(gift == nullptr)
            continue;
        delete gift;
    }
    levelupGiftArray.clear();

    for (i = 0; i < enchantingGiftArray.size(); i++) {
        LevelUpGift *gift = enchantingGiftArray[i];
        if(gift == nullptr)
            continue;
        delete gift;
    }
    enchantingGiftArray.clear();
}

void PlayerGiftCenter::loadLevelGifts()
{
    int i = 0;
    for (i = 0; i < GIFT_MAX_LEVEL; i++) {
        levelupGiftArray.push_back(nullptr);
    }
    QueryResult result = CharacterDatabase.Query("select target_level,email_subject ,email_body ,email_sender_char_guid,klgcd.gift_type ,klgcd.item_entry_id,klgcd.item_count  from kkk_levelup_gift_cfg klgc left join  kkk_levelup_gift_cfg_detail klgcd on klgc.gift_type = 'LEVELUP' and klgc.id  = klgcd.gift_cfg_id where klgc.enabled  =1 and klgcd.enabled  =1 order by target_level ");
    if (!result) {
        LOG_WARN("kkk gift module.loading", ">> Loaded 0 gifts. DB table `kkk_levelup_gift_cfg`  or `kkk_levelup_gift_cfg_detail` maybe empty.");
        return;
    }
    do {
        Field *fields = result->Fetch();
        buildGift(levelupGiftArray,fields,GIFT_MAX_LEVEL);
    } while (result->NextRow());
}

void PlayerGiftCenter::loadEnchantingGifts()
{
    int i = 0;
    for (i = 0; i < CRAFTING_SKILL_MAX_LEVEL; i++) {
        enchantingGiftArray.push_back(nullptr);
    }
     QueryResult result = CharacterDatabase.Query("select target_level,email_subject ,email_body ,email_sender_char_guid,klgcd.gift_type ,klgcd.item_entry_id,klgcd.item_count  from kkk_levelup_gift_cfg klgc left join  kkk_levelup_gift_cfg_detail klgcd on klgc.gift_type = 'ENCHANTING' and klgc.id  = klgcd.gift_cfg_id where klgc.enabled  =1 and klgcd.enabled  =1 order by target_level ");
    if (!result) {
        LOG_WARN("kkk gift module.loading", ">> Loaded 0 gifts. DB table `kkk_levelup_gift_cfg`  or `kkk_levelup_gift_cfg_detail` maybe empty.");
        return;
    }
    do {
        Field *fields = result->Fetch();
        buildGift(enchantingGiftArray,fields,CRAFTING_SKILL_MAX_LEVEL);
    } while (result->NextRow());
}

void PlayerGiftCenter::buildGift(vector<LevelUpGift *> &targetGiftArray, Field *fields, int arrayMaxItems)
{
    uint32 targetLevel = fields[0].Get<uint32>();
    if (targetLevel >= arrayMaxItems) {
        LOG_WARN("kkk gift module.loading", ">> Gift's target level large then %d", arrayMaxItems);
        return;
    }
    uint32 senderGuid = fields[3].Get<uint32>();

    // build levelup gift
    if (targetGiftArray[targetLevel] == nullptr) {
        string subject = fields[1].Get<string>();
        string body = fields[2].Get<string>();
        targetGiftArray[targetLevel] = new LevelUpGift(subject, body, targetLevel, senderGuid);
    }

    uint32 giftType = fields[4].Get<uint32>();
    uint32 itemCount = fields[6].Get<uint32>();

    // enrich gift by type.
    if (giftType == KKK_GIFT_TYPE_MONEY) {
        targetGiftArray[targetLevel]->setMonney(itemCount);
    } else if (giftType == KKK_GIFT_TYPE_ITEM 
                || giftType == KKK_GIFT_TYPE_RENAME) {
        uint32 itemEntryId = fields[5].Get<uint32>();
        LeveUpGiftEntry *giftEntry = new LeveUpGiftEntry(giftType, itemEntryId, itemCount);
        targetGiftArray[targetLevel]->addGift(giftEntry);
    } else {
        LOG_WARN("kkk gift module.loading", ">> Gift's type error! (should be 0 or 1)");
        return;
    }
}


// init gift center .(load gift config from DB)
void PlayerGiftCenter::init()
{
    clear();

    // init level up gifts
    loadLevelGifts();

    
    //init enchanting gifts
    loadEnchantingGifts();
    
}

LevelUpGift *PlayerGiftCenter::getGiftByeLevel(uint32 level)
{
    if (level >= GIFT_MAX_LEVEL) {
        LOG_WARN("kkk gift module.getGiftByeLevel", ">> Gift's target level large then GIFT_MAX_LEVEL");
        return nullptr;
    }
    return levelupGiftArray[level];
}

LevelUpGift* PlayerGiftCenter::getGiftByEnchantingLevel(uint32 enchantingLevel)
{
    if (enchantingLevel >= CRAFTING_SKILL_MAX_LEVEL) {
        LOG_WARN("kkk gift module.getGiftByeLevel", ">> Gift's target level large then CRAFTING_SKILL_MAX_LEVEL");
        return nullptr;
    }
    return enchantingGiftArray[enchantingLevel];
}

vector<LevelUpGift*> PlayerGiftCenter::getAllGift()
{
    return levelupGiftArray;
}
